<?php
/**
 * 基本配置
 */
class ControllerConfigMenu extends Controller {

	private $error = array();

	protected function init(){
		$this->load_language('config/menu');

		$this->document->setTitle($this->language->get('heading_name_title'));

		$this->load->model('config/menu');

	}

	public function index() {
		$this->init();
		$this->getList();
	}

	private function getForm() {
		$this->load->model('config/common');
		$commons = $this->model_config_common->getAllCommons();
		$this->data['commons'] = $commons;
		$menu_name="";
		$menu_status ="";
		$common_id = 0;
		$menu_routes = array();
		if (isset($this->request->get['menu_id'])) {
			$menuInfo = $this->model_config_menu->getMenu($this->request->get['menu_id']);
			$this->data['menuInfo'] = $menuInfo;
			$menu_name = $menuInfo['menu_name'];
			$menu_status =  $menuInfo['menu_status'];
			$common_id =  $menuInfo['common_id'];
			$menu_routes = $menuInfo['menu_route'];
		}
		$this->data['menu_routes'] = $menu_routes;
		$this->data['menu_name'] = $menu_name;
		$this->data['menu_status'] = $menu_status;
		$this->data['common_id'] = $common_id;
		$url = "";
		if(isset($this->request->get['menu_id'])) {
			$url .= "&menu_id=".$this->request->get['menu_id'];
		}

		if (isset($this->request->get['menu_id'])) {
			$this->data['action'] = $this->url->link('config/menu/update', 'token=' . $this->session->data['token'].$url, 'SSL');
		}else{
			$this->data['action'] = $this->url->link('config/menu/insert', 'token=' . $this->session->data['token'] , 'SSL');
		}

		$this->data['cancel'] = $this->url->link('config/menu', 'token=' . $this->session->data['token'] , 'SSL');
		$this->data['token'] =  $this->session->data['token'];
		
		$this->template = 'config/menu_form.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
	}

	public function insert() {
		$this->init();
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_config_menu->addMenu($this->request->post);
			$this->redirectToList();
		}
		$this->getForm();
	}

	private function getList() {

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data = array(
			'start' => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit' => $this->config->get('config_admin_limit')
		);


		$this->data['menus'] = array();

		$user_total = $this->model_config_menu->getTotalMenus();

		$results = $this->model_config_menu->getMenus($data);

		foreach ($results as $result) {
			$action = array();

			$action[] = array(
				'text' => $this->language->get('text_edit'),
				'type' => "edit",
				'href' => $this->url->link('config/menu/update', 'token=' . $this->session->data['token'] . '&menu_id=' . $result['menu_id'] , 'SSL')
			);

			$action[] = array(
				'text' => "发布",
				'type' => "publish",
				'href' => $this->url->link('config/menu/publish',  'menu_id=' . $result['menu_id']."&status=1&type=publish" , 'SSL')
			);

			$action[] = array(
				'text' => "取消发布",
				'type' => "cancel",
				'href' => $this->url->link('config/menu/publish',  'menu_id=' . $result['menu_id']."&status=0&type=cancel"  , 'SSL')
			);

			$this->data['menus'][] = array(
				'menu_id'    => $result['menu_id'],
      			'menu_name'    => $result['menu_name'],
      			'menu_body'    => $result['menu_body'],
				'actions'     => $action,
      			'menu_status'     => ((isset($result['menu_status'])&&$result['menu_status']==0) ? $this->language->get('text_disabled') : $this->language->get('text_enabled')),
      			'selected'   => isset($this->request->post['selected']) && in_array($result['id'], $this->request->post['selected']),
			);
		}

		$url = "";

		if(isset($this->request->get['menu_id']))
		{
			$url = "&menu_id="+$this->request->get['menu_id'];
		}

		if (isset($this->request->post['status'])) {
			$this->data['status'] = $this->request->post['status'];
		} elseif (isset($user_info)) {
			$this->data['status'] = $user_info['status'];
		} else {
			$this->data['status'] = 0;
		}

		$this->data['insert'] = $this->url->link('config/menu/insert', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['delete'] = $this->url->link('config/menu/delete', 'token=' . $this->session->data['token'].$url, 'SSL');

		$this->data['token'] = $this->session->data['token'];
		$pagination = new Pagination();
		$pagination->total = $user_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('config/menu', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
		$this->data['pagination'] = $pagination->render();

		
		$this->template = 'config/menu_list.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
		
	}

	public function delete() {
		$this->init();
		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $menu_id) {
				$this->model_config_menu->deleteMenu($menu_id);
			}
			$this->redirectToList();
		}

		$this->getList();
	}


	public function update() {
		$this->init();

		if (isset($this->request->get['menu_id'])&&($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_config_menu->editMenu($this->request->get['menu_id'],$this->request->post);
			$this->redirectToList();
		}
		$this->getForm();
	}

	private function validateDelete() {
		/*if (!$this->user->hasPermission('modify', 'catalog/article')) {
			$this->error['warning'] = sprintf($this->language->get('error_permission'),$this->language->get('heading_title'));
			}
			*/
		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function publish(){

		$this->init();
		$this->load->library('json');
		if (isset($this->request->get['menu_id'])) {
			//获取菜单信息
			$menus = $this->coverMenu($this->request->get['menu_id']);
			//获取基本信息
			$menuInfo = $this->model_config_menu->getMenu($this->request->get['menu_id']);
			$menuPostString = $menus;
			$menuPostString =str_replace("&quot;","\"", $menuPostString);
			$menuPostString = str_replace("'","", $menuPostString);
		}
		
		$json = array();
		$this->load->model('config/common');
		//获取基本配置列表
		$common =$this->model_config_common->getCommon($menuInfo['common_id']);
		$json['common_id'] = $common['common_id'];
		$tonen = weiUtil::getAccessToken($common['appid'], $common['appsecret']);
		//停用
		if(isset($this->request->get['type'])&&$this->request->get['type']=='cancel')
		{
			$response = weiUtil::deleteMenu($menuPostString,$tonen);
			if(isset($response)&&$response['errcode']==0)
			{
				$this->model_config_menu->updateStatus($this->request->get['menu_id'],$this->request->get['status']);
				$json['status'] ="success" ;
				$json['errmsg'] ="取消菜单成功" ;
			}else{
				$json['status'] =$response['errcode'] ;
				$json['errmsg'] =$response["errmsg"] ;
			}
		}else if(isset($this->request->get['type'])&&$this->request->get['type']=='publish'){
			if($this->validator()&&isset($this->request->get['status']))
			{

				$response = weiUtil::createMenu($menuPostString,$tonen);
				//创建成功
				if(isset($response)&&$response['errcode']==0)
				{
					$this->model_config_menu->updateStatus($this->request->get['menu_id'],$this->request->get['status']);
					$json['status'] ="success" ;
					$json['errmsg'] ="创建成功" ;
				}
				else{
					$json['status'] =$response['errcode'] ;
					$json['errmsg'] =$response["errmsg"] ;
				}
			}

		}
		$this->response->setOutput(Json::encode($json));
		
	}




	private function coverMenu($menu_id)
	{
		$this->load->library('json');
		$menus = array();

		$parentMenus = $this->model_config_menu->getParentMenus($this->request->get['menu_id']);

		if(isset($parentMenus))
		{
			foreach ($parentMenus as $parentMenu) {

				$subs = array();
				$subMenus = $this->model_config_menu->getSubMenu($parentMenu['menu_route_id']);
				if(isset($subMenus)&&count($subMenus)>0)
				{
					foreach ($subMenus as $subMenu) {
						if($subMenu['menu_type']=='click')
						{
							$subs[] = array(
							"type" => urlencode ($subMenu['menu_type']),
							"name" => urlencode ($subMenu['display_name']),
							'key' => urlencode ($subMenu['menu_url'])
							);
						}
					else if($subMenu['menu_type']=='pic_sysphoto'||$subMenu['menu_type']=='location_select'){
						$subs[] = array(
							"type" => urlencode ($subMenu['menu_type']),
							"name" => urlencode ($subMenu['display_name']),
							'key' => urlencode ($subMenu['menu_url'])
							);
					}
						else{
							$subs[] = array(
							"type" => urlencode ($subMenu['menu_type']),
							"name" => urlencode ($subMenu['display_name']),
							'url' => urlencode ($subMenu['menu_url'])
							);
						}
					}
				$parent = array(
					"name" => urlencode ($parentMenu["display_name"]),
					"sub_button" => $subs,
				);
				}else{
					if($parentMenu['menu_type']=='click'){
						$parent = array(
							"name" => urlencode ($parentMenu["display_name"]),
							"type" => urlencode ($parentMenu['menu_type']),
							"key" => urlencode ($parentMenu['menu_url']),
						);
					}else if($parentMenu['menu_type']=='pic_sysphoto'||$parentMenu['menu_type']=='location_select'){
						$parent = array(
							"name" => urlencode ($parentMenu["display_name"]),
							"type" => urlencode ($parentMenu['menu_type']),
							"key" => urlencode ($parentMenu['menu_url']),
						);
					}
					else{
						$parent = array(
							"name" =>urlencode ( $parentMenu["display_name"]),
							"type" => urlencode ($parentMenu['menu_type']),
							"url" => urlencode ($parentMenu['menu_url']),
						);
					}
				}
				$menus['button'][] =$parent;
			}
		}
		
		return urldecode ( Json::encode($menus ) );
	}

	public function validator(){
		return true;
	}



	private function validateForm() {
		if (!$this->error) {
			return TRUE;
		} else {
			$this->error['warning'] = $this->language->get('error_required_data');
			return FALSE;
		}
	}
	private function redirectToList(){
		$this->session->data['success'] = sprintf($this->language->get('text_success'),$this->language->get('heading_title'));

		$url=$this->getUrlParameters();

		$this->redirect(HTTPS_SERVER . 'index.php?route=config/menu&token=' . $this->session->data['token'] . $url);
	}

	public function getUrlParameters(){
		$url = '';

		$url=$this->getMenuUrlParameters();

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		return $url;
	}

	private function getMenuUrlParameters(){
		$url = '';

		if (isset($this->request->get['filter_title'])) {
			$url .= '&filter_title=' . $this->request->get['filter_title'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['filter_date_add'])) {
			$url .= '&filter_date_add=' . $this->request->get['filter_date_add'];
		}

		if (isset($this->request->get['filter_article_category_id'])) {
			$url .= '&filter_article_category_id=' . $this->request->get['filter_article_category_id'];
		}

		return $url;
	}


	
}
?>